package com.itheima.web.servlet;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 替换HttpServlet，根据请求的最后一段路径来进行方法分发
 */



public class BaseServlet extends HttpServlet {
    //根据请求的最后一段路径进行方法分发
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求路径
        String requestURI = req.getRequestURI();  //    /brand-case/brand/selectAll
//        System.out.println(requestURI);
        //2.获取最后一段路径
        int index = requestURI.lastIndexOf('/');
        String methodName = requestURI.substring(index + 1);
//        System.out.println("methodName = " + methodName);
        //3.执行方法
        //3.1获取BrandServlet或者UserServlet字节码对象class
//        System.out.println(this);
        Class<? extends BaseServlet> cls = this.getClass();
        //3.2获取方法的Method对象
        try {
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        //3.3执行方法


    }
}
